package cn.itcast.pattern.proxy.cglib_proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.smartcardio.TerminalFactory;
import java.lang.reflect.Method;

/*
    代理对象工厂
 */
public class ProxyFactory implements MethodInterceptor {

    //声明火车站对象
    private TrainStation station = new TrainStation();

    public TrainStation getProxyObject(){
        //创建Enhancer对象  类似于JDK代理对象中的Proxy类
        Enhancer enhancer = new Enhancer();

        //设置父类的字节码对象
        enhancer.setSuperclass(TrainStation.class);

        //设置回调函数
        enhancer.setCallback(this);
        //创建代理对象
        TrainStation proxyObject = (TrainStation) enhancer.create();

        return proxyObject;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("方法执行了,代售点收取一定的费用");
        station.sell();
        Object o1 =  method.invoke(station,objects);
        return o1;
    }
}
